<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 通知公告
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-input v-model="query.title" placeholder="标题" class="filter-item handle-input mr10"></el-input>
                <el-button type="primary" icon="el-icon-search" class="filter-item" @click="handleSearch">搜索</el-button>
                <el-button type="primary" icon="el-icon-plus" class="filter-item" @click="handleAdd">新增</el-button>
            </div>
            <el-table
                    v-loading="loading"
                    :data="tableData"
                    border
                    class="table"
                    ref="multipleTable"
                    header-cell-class-name="table-header"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column prop="title" label="标题"></el-table-column>
                <el-table-column label="类型" align="center" >
                    <template slot-scope="scope">
                        <el-tag type="success">
                            {{selectDictLabel(form.typeOptions, scope.row.type)}}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="状态" align="center" >
                    <template slot-scope="scope">
                        <el-tag type="success">
                            {{selectDictLabel(form.statusOptions, scope.row.status)}}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="remark" label="备注"></el-table-column>
                <el-table-column prop="createTime" label="创建时间">
                    <template slot-scope="scope">
                        <span>{{ parseDateTime(scope.row.createTime) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope">
                        <el-button
                                type="text"
                                icon="el-icon-edit"
                                :disabled="userId == scope.row.creator ? false : true"
                                @click="handleEdit(scope.$index, scope.row)"
                        >编辑</el-button>
                        <el-button
                                type="text"
                                icon="el-icon-delete"
                                class="red"
                                @click="handleDelete(scope.$index, scope.row)"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                        background
                        layout="total, prev, pager, next"
                        :current-page="query.current"
                        :page-size="query.size"
                        :total="pageTotal"
                        @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" :visible.sync="editVisible" width="50%">
            <el-form ref="form" :model="form" :rules="rules" label-width="70px">
                <el-form-item label="标题" prop="title">
                    <el-input v-model="form.title"></el-input>
                </el-form-item>
                <el-form-item label="类型">
                    <el-select v-model="form.type" placeholder="请选择">
                        <el-option
                                v-for="item in form.typeOptions"
                                :key="item.value"
                                :label="item.name"
                                :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="状态">
                    <el-select v-model="form.status" placeholder="请选择">
                        <el-option
                                v-for="item in form.statusOptions"
                                :key="item.value"
                                :label="item.name"
                                :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input type="textarea" v-model="form.remark"></el-input>
                </el-form-item>
                <el-form-item label="内容">
                    <editor-bar v-model="form.content" :isClear="form.isClear" @change="change"></editor-bar>
                </el-form-item>
                <el-form-item label="范围类型">
                    <el-select v-model="form.dataScopeType" placeholder="请选择">
                        <el-option label="不限制部门" value="1"></el-option>
                        <el-option label="本人所属部门" value="2"></el-option>
                        <el-option label="指定本人所属部门" value="3"></el-option>
                        <el-option label="本人查看" value="4"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="部门" v-if="form.dataScopeType == '3'">
                    <el-select v-model="form.deptIdArr" multiple placeholder="请选择">
                        <el-option
                                v-for="item in form.currentUserDepts"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit('form')">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import { sysNotice,updateSysNotice,saveSysNotice,delSysNotice } from '../../api/sysNotice';
    import { currentUserSysDeptList } from '../../api/sysDept';

    import EditorBar from '../../components/common/WangEditor'
    export default {
        name: 'sys-notice-list',
        data() {
            return {
                userId: localStorage.getItem('userId'),
                // 遮罩层
                loading: true,
                query: {
                    title: '',
                    current: 1,
                    size: 10
                },
                tableData: [],
                delList: [],
                editVisible: false,
                pageTotal: 0,
                form: {
                    title:"",
                    type:"",
                    status:"",
                    remark:"",
                    isClear: false,
                    content:"",
                    typeOptions: [],
                    dataScopeType:"",
                    currentUserDepts:[],
                    deptIdArr:[],
                    statusOptions: [{
                        value: '1',
                        name: '正常'
                    }, {
                        value: '2',
                        name: '关闭'
                    }]
                },
                rules: {
                    title: [
                        { required: true, message: '请输入名称', trigger: 'blur' },
                        { min: 5, max: 200, message: '长度在 5 到 200 个字符', trigger: 'blur' }
                    ]
                },
                idx: -1,
                id: -1
            };
        },
        components: { EditorBar },
        created() {
            this.getDicts("sys_notice_type").then(res => {
                this.form.typeOptions = res.data;
                this.defaultform = JSON.parse(JSON.stringify(this.form));
            });
            this.getData();
        },
        destroyed() {
            this.defaultform = null;
        },
        methods: {
            // 获取 easy-mock 的模拟数据
            getData() {
                this.loading = true;
                sysNotice(this.query).then(res => {
                    this.loading = false;
                    this.tableData = res.data;
                    this.pageTotal = res.count;
                });
            },
            // 触发搜索按钮
            handleSearch() {
                this.$set(this.query, 'current', 1);
                this.getData();
            },
            // 删除操作
            handleDelete(index, row) {
                // 二次确认删除
                this.$confirm('确定要删除吗？', '提示', {
                    type: 'warning'
                })
                    .then(() => {
                        delSysNotice(row.id).then(res => {
                            if (res.code == 0) {
                                this.editVisible = false;
                                this.$message.success(`删除成功`);
                                this.getData();
                            } else {
                                this.$message.error(res.msg);
                                return false;
                            }
                        });
                        //this.tableData.splice(index, 1);
                    })
                    .catch(() => {});
            },
            handleAdd(){
                this.form = Object.assign({}, this.defaultform);
                this.editVisible = true;
                // 查询当前用户部门
                currentUserSysDeptList(this.query).then(res => {
                    // 赋值
                    this.form.currentUserDepts = res.sysDeptList;
                });
                this.$nextTick(()=>{
                    this.$refs['form'].clearValidate();
                })
            },
            // 编辑操作
            handleEdit(index, row) {
                this.idx = index;
                this.form.id = row.id;
                this.form.title = row.title;
                this.form.type = row.type;
                this.form.status = row.status;
                this.form.remark = row.remark;
                this.form.content = row.content;
                this.editVisible = true;
                // 需要用户选中值deptIdArr
                // 查询当前用户部门
                currentUserSysDeptList(this.query).then(res => {
                    // 赋值
                    this.form.currentUserDepts = res.sysDeptList;
                });
                this.form.dataScopeType = row.dataScopeType;
                this.form.deptIds = row.deptIds;
                let deptIds = row.deptIds;
                let deptIdArr = [];
                if (deptIds != null && deptIds != "") {
                    deptIds.split(',').forEach(item => {
                        deptIdArr.push(parseInt(item));
                    })
                }
                this.form.deptIdArr = deptIdArr;
                this.$nextTick(()=>{
                    this.$refs['form'].clearValidate();
                })
            },
            change(val) {
                // console.log(val)
            },
            // 保存编辑
            saveEdit(formName) {
                // ajax提交至后台
                this.$refs[formName].validate((valid) => {
                    if (!valid) {
                        console.log('error submit!!');
                        return false;
                    }
                    let deptIdArr = this.form.deptIdArr;
                    if (this.form.dataScopeType == "3" && (deptIdArr == null || deptIdArr.length <= 0)) {
                        this.$message.error(`请选择指定部门`);
                        return false;
                    }
                    if (deptIdArr != null && deptIdArr.length > 0) {
                        this.form.deptIds = deptIdArr.join(",");
                    }
                    if (this.form.id) {
                        updateSysNotice(this.form).then(res => {
                            if (res.code == 0) {
                                this.editVisible = false;
                                this.$message.success(`修改成功`);
                                this.getData();
                            } else {
                                this.$message.error(res.msg);
                                return false;
                            }
                        });
                    } else {
                        saveSysNotice(this.form).then(res => {
                            if (res.code == 0) {
                                this.editVisible = false;
                                this.$message.success(`修改成功`);
                                this.getData();
                            } else {
                                this.$message.error(res.msg);
                                return false;
                            }
                        });
                    }
                });
            },
            // 分页导航
            handlePageChange(val) {
                this.$set(this.query, 'current', val);
                this.getData();
            }
        }
    };
</script>

<style scoped>
    .handle-box {
        margin-bottom: 20px;
    }

    .handle-select {
        width: 120px;
    }

    .handle-input {
        width: 300px;
        display: inline-block;
    }
    .table {
        width: 100%;
        font-size: 14px;
    }
    .red {
        color: #ff0000;
    }
    .mr10 {
        margin-right: 10px;
    }
    .table-td-thumb {
        display: block;
        margin: auto;
        width: 40px;
        height: 40px;
    }
</style>
